const citySelector = requirePlugin('citySelector');
const app = getApp()
import * as echarts from './ec-canvas/echarts';
const myRequest = require('../../../utils/request'); // 导入整个模块



Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 0,
    city: '广州', //显示当前定位城市
    province: '广东省',
    daily: [],
    active: 0,
    activeindex: 0, //当前天气预报日期下标,
    nowdaily: '',
    hourly: [],
    templist: [],
    scrollTop:0,
    pointLeft:0,
    ec: {
      disableTouch: true,
      lazyLoad: true,
    },
    opinion:[]
  },
   // 滚动事件监听
   onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop,
    })
  },
  onScroll: function(e) {
    // 更新滚动位置
    this.setData({
      scrollOffset: e.detail.scrollTop
    });
  },
  onReady() {
    // 获取组件
    this.ecComponent = this.selectComponent('#mychart-dom-bar');
  },
  initFn() {
    // 获取数据后
    this.ecComponent.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      var option = {
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.data.hourly,
         show: false
        },
        grid: {
          // 让图表占满容器
          top: "30px",
          left: "25px",
          right: "15px",
          bottom: "30px",
        },


        yAxis: {
          type: 'value', 
          splitNumber: 5,
        },
        lineStyle: {
          color: '#FDD692'
        },
        color: '#FBFFB9',
        series: [{
          data: this.data.templist,
          type: 'line',
          areaStyle: {}
        }]

      };
      chart.setOption(option);
      return chart
    })



  },

  onLoad(options) {
    this.getdateweek()
    this.getweather()
    this.getcity()
    this.getnowweather()
    this.getqualitydata()
     this.updatepoint(this.data.activeindex)
  },
  // 从城市选择器插件返回后，在页面的onShow生命周期函数中能够调用插件接口，获取cityInfo结果对象
  onShow() {
    if (citySelector.getCity())
      this.setData({
        city: citySelector.getCity().name,
      })
    this.getweather()
    this.getnowweather()
    this.getqualitydata()
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop,
    })
  },
  switchcity() {
    const key = 'M54BZ-LTIW3-KEG3N-O245R-BVE52-EIBEX'; // 使用在腾讯位置服务申请的key
    const referer = 'wx63ffb7b7894e99ae'; // 调用插件的app的名称
    wx.navigateTo({
      url: `plugin://citySelector/index?key=${key}&referer=${referer}`,
    })
  },
  //逆地址解析
  async getcity() {

    let that = this
    // 如果用户更新授权信息，则调用 getLocation 获取用户地理位置信息
    const res = await wx.getLocation()
    let {
      longitude,
      latitude
    } = res;
    wx.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
      method: 'GET',
      data: {
        key: '3a2e1f6885f7056042443f10052b418d',
        location: longitude + "," + latitude
      },
      success(res) {
        that.setData({
          city: res.data.regeocode.addressComponent.city.slice(0, -1),
          province: res.data.regeocode.addressComponent.province
        })
        app.globalData.city = res.data.regeocode.addressComponent.province
        that.getweather()

      }
    })
  },
  getweather() {
    let that = this
    myRequest.get('/get/weatherdata', {key: this.data.city}).then(res=>{
      that.setData({
        daily: res.data.daily
      })
    })
  },
  getnowweather() {
    let that = this
    myRequest.get('/get/weather24data', {key: this.data.city}).then(res=>{
      let hourly = []
      let templist = []
      res.data.hourly.forEach(val => {
        hourly.push(val.fxTime),
          templist.push(val.temp)
      })
      that.setData({
        nowdaily: res.data.hourly,
        hourly,
        templist
      })
      that.initFn()
    })
    
  },
  getqualitydata(){
    let that = this
    myRequest.get('/get/qualitydata', {key: this.data.city}).then(res=>{
      that.setData({
        opinion: res.data.daily
      })
    })
    
  },

  // 格式化日期为 yyyy-MM-dd 格式
  formatDate(date) {
    let m = (date.getMonth() + 1).toString().padStart(2, '0');
    let d = date.getDate().toString().padStart(2, '0');
    return `${m}/${d}`;
  },

  // 获取星期几
  getWeekday(date) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[date.getDay()];
  },
  getdateweek() {
    const datesWeek = []
    //计算天数
    // 创建一个函数来获取指定天数后的日期和星期几
    // 填充数组对象
    datesWeek.push({
      date: this.formatDate(new Date()),
      week: this.getWeekday(new Date())
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 2 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 2 * 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 4 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 4 * 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 5 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 5 * 24 * 60 * 60 * 1000))
    }, {
      date: this.formatDate(new Date(new Date().getTime() + 6 * 24 * 60 * 60 * 1000)),
      week: this.getWeekday(new Date(new Date().getTime() + 6 * 24 * 60 * 60 * 1000))
    }, );
    this.setData({
      datesWeeks: datesWeek
    })

  },
  updatepoint(){
    let that=this
    const index=this.data.activeindex
    wx.nextTick(() => {
      const query = wx.createSelectorQuery();
      query.select(`#box${index}`).boundingClientRect();
      query.exec(function(res) {
        console.log(res[0].left);
        if (res && res[0]) {
          // 计算中间点的左侧位置
          const boxLeft = res[0].left + res[0].width / 2-20;
          that.setData({
            pointLeft: boxLeft
          });
        } else {
          console.error('未找到元素或元素尚未渲染');
        }
      });
    });
  },
  //点击日期时
  clickdate(e) {
    this.setData({
      activeindex: e.currentTarget.dataset.activeindex
    })
    const index=e.currentTarget.dataset.activeindex
    this.updatepoint(index)
    this.initFn()
    // this.getqualitydata()
  },

  

})